"use strict";

const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const collection = db.collection("coupons");
const articleCollection = db.collection("news-articles-image");
const couponUsageCollection = db.collection("coupon-usage");

// 新增：更新活动的优惠券信息
// 将函数移到模块外部
async function updateArticleCouponInfo(articleId, coupon_id) {
  try {
    await articleCollection.doc(articleId).update({
      coupon_id,
    });
    return {
      code: 200,
      message: "活动优惠券信息更新成功",
    };
  } catch (e) {
    console.error("更新活动优惠券信息失败:", e);
    throw e;
  }
}

module.exports = {
  async getCoupons(userId) {
    try {
      const res = await collection
        .where({
          user_id: userId,
        })
        .get();
      return {
        code: 200,
        data: res.data,
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  async addCoupon(data) {
    try {
      // 验证折扣率范围
      if (data.discount && (data.discount < 1 || data.discount > 99)) {
        return {
          code: 400,
          message: "折扣率必须在1-99之间",
        };
      }

      const res = await collection.add({
        ...data,
        status: data?.status || 0, // 默认未发布
        create_date: Date.now(),
        last_modify_date: Date.now(),
      });

      // 如果有关联的活动ID，更新活动的优惠券信息
      // 修改这里的调用方式
      if (data.category_id) {
        await updateArticleCouponInfo(data.category_id, res.id);
      }

      return {
        code: 200,
        data: res.id,
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  async updateCoupon(id, data) {
    try {
      // 验证折扣率范围
      if (data.discount && (data.discount < 1 || data.discount > 99)) {
        return {
          code: 400,
          message: "折扣率必须在1-99之间",
        };
      }

      await collection.doc(id).update({
        ...data,
        last_modify_date: Date.now(),
      });

      // 如果有关联的活动ID，更新活动的优惠券信息
      // 这里也需要修改
      if (data.category_id) {
        await updateArticleCouponInfo(data.category_id, id);
      }

      return {
        code: 200,
        message: "更新成功",
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  async getCoupon(id) {
    try {
      const res = await collection.doc(id).get();
      return {
        code: 200,
        data: res.data[0],
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  /**
   * 检查用户是否已领取优惠券
   * @param {Object} params
   * @param {String} params.coupon_id 优惠券ID
   * @param {String} params.user_id 用户ID
   * @returns {Object} 返回检查结果
   */
  async checkCouponReceived(params) {
    try {
      const { coupon_id, user_id } = params;

      const result = await couponUsageCollection
        .where({
          coupon_id: coupon_id,
          user_id: user_id,
          status: db.command.in([0, 1]), // 检查是否已领取或已使用
        })
        .get();

      return {
        code: 200,
        data: {
          received: result.data.length > 0,
          usage: result.data[0] || null,
        },
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  /**
   * 领取优惠券
   * @param {Object} params
   * @param {String} params.coupon_id 优惠券ID
   * @param {String} params.user_id 用户ID
   * @param {String} params.validity 优惠券有效期
   * @returns {Object} 返回领取结果
   */
  async receiveCoupon(params) {
    try {
      const { coupon_id, user_id, validity } = params;

      // 检查是否已领取
      const result = await couponUsageCollection
        .where({
          coupon_id: coupon_id,
          user_id: user_id,
          status: db.command.in([0, 1]), // 检查是否已领取或已使用
        })
        .get();

      if (result.data.length > 0) {
        return {
          code: 400,
          message: "您已领取过该优惠券",
        };
      }

      // 创建领取记录
      const addResult = await couponUsageCollection.add({
        coupon_id,
        user_id,
        status: 0, // 已领取
        receive_date: Date.now(),
        expire_date: new Date(validity).getTime(),
      });

      return {
        code: 200,
        data: addResult.id,
        message: "领取成功",
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  /**
   * 获取用户的优惠券列表
   * @param {String} user_id 用户ID
   * @returns {Object} 返回优惠券列表
   */
  async getUserCoupons(user_id) {
    try {
      const currentTime = Date.now();
      const usageResult = await couponUsageCollection
        .aggregate()
        .match({
          user_id,
        })
        .lookup({
          from: "coupons",
          let: { coupon_manager_coupon_id: "$coupon_id" },
          pipeline: $.pipeline()
            .match(
              dbCmd.expr(
                $.and([
                  $.eq(["$_id", "$$coupon_manager_coupon_id"]),
                  $.gt(["$validity", currentTime]), // 只查找未过期的优惠券
                ])
              )
            )
            .project({
              _id: 1,
              name: 1,
              discount: 1,
              validity: 1,
              cutomImage: 1,
              status: 1,
              receive_date: 1,
              expire_date: 1,
            })
            .done(),
          as: "coupon_info",
        })
        .sort({
          "coupon_info.0.validity": -1,
        })
        .end();

      // 如果没有领取记录，直接返回空数组
      if (!usageResult.data || usageResult.data.length === 0) {
        return {
          code: 200,
          data: [],
        };
      }

      return {
        code: 200,
        data: usageResult.data,
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },

  /**
   * 核销优惠券
   * @param {Object} params
   * @param {String} params.coupon_id 客户领取之后，usage表中的_id
   * @param {String} params.user_id 用户ID
   * @returns {Object} 返回核销结果
   */
  async verifyScannedCoupon(params) {
    try {
      const { coupon_id: usage_id, user_id, manager_id, merchant_id } = params;

      // 通过聚合操作，在usage表中，找到对应的优惠券信息
      const usage = await couponUsageCollection
        .aggregate()
        .match({
          _id: usage_id,
        })
        .lookup({
          from: "coupons",
          let: { coupon_manager_coupon_id: "$coupon_id" },
          pipeline: $.pipeline()
            .match(
              dbCmd.expr($.and([$.eq(["$_id", "$$coupon_manager_coupon_id"])]))
            )
            .project({
              _id: 1,
              status: 1,
            })
            .done(),
          as: "coupon_info",
        })
        .end();

      // 检查优惠券是否存在
      if (usage.data.length === 0) {
        return {
          code: 404,
          message: "优惠券不存在，或用户未领取",
        };
      }

      // 检查优惠券是否已过期，通过status === 3来判断，因为过期后会被设置为3
      if (usage.data[0].coupon_info[0].status === 3) {
        return {
          code: 400,
          message: "优惠券已过期",
        };
      }

      // 检查优惠券是否已被核销，通过status === 1来判断，因为核销后会被设置为1
      if (usage.data[0].status === 1) {
        return {
          code: 400,
          message: "优惠券已被核销",
        };
      }

      // 核销优惠券
      const usageRecord = usage.data[0];
      const currentTime = Date.now();
      await couponUsageCollection.doc(usageRecord._id).update({
        status: 1, // 1 表示已使用
        user_id, // 客户ID
        merchant_id, // 商户ID
        manager_id, // 在后台注册并且通过的商家，旗下的管理员ID
        use_date: currentTime, // 核销时间
      });

      return {
        code: 200,
        data: {},
      };
    } catch (e) {
      return {
        code: 500,
        message: e.message,
      };
    }
  },
};
